package com.agile.leetcode.easy.bigNumCalculate;

/**
 * 大数相减
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/9 22:08
 */
public class BigNumSubtract {
    public static void main(String[] args) {
        BigNumSubtract subtract = new BigNumSubtract();
        String num1 = "88";
        String num2 = "77";
        String result = subtract.subtract(num2, num1);
        System.out.println(result);
    }

    public String subtract(String num1, String num2) {
        boolean b = compareNum(num1, num2);
        char sign = '+';
        // 判断是否是num1大于nun2
        if (!b) {
            // 此时需要交换数字
            String temp = num1;
            num1 = num2;
            num2 = temp;
            // 此时应该为负数
            sign = '-';
        }
        // 计算，此时num1>num2
        // 拿到长度
        int length1 = num1.length() - 1;
        int length2 = num2.length() - 1;
        // n拿到字符数组
        char[] charNum1 = num1.toCharArray();
        char[] charNum2 = num2.toCharArray();
        StringBuilder builder = new StringBuilder();
        // 借位
        int borrow = 0;
        while (length1 >= 0 || length2 >= 0) {
            int n1 = length1 >= 0 ? (charNum1[length1--] - '0') : 0;
            int n2 = length2 >= 0 ? (charNum2[length2--] - '0') : 0;
            // 相减
            int num = n1 - n2 - borrow;
            // 是否需要借位
            if (num < 0) {
                // 借位
                borrow = 1;
                num += 10;
            }
            // 加入字符拼接
            builder.append(num);
        }
        // 翻转
        StringBuilder reverse = builder.reverse();
        // 去掉没用的0
        int index = 0;
        while (index < reverse.length() && reverse.charAt(index) == '0') {
            index++;
        }
        // 如果两数字相同
        if (index == reverse.length()) {
            return "0";
        }
        // 如果是正数
        if (sign == '+') {
            return reverse.substring(index);
        } else {
            return sign + reverse.substring(index);
        }

    }

    /**
     * 比较两个数字的大小
     *
     * @param num1
     * @param num2
     * @return
     */
    private boolean compareNum(String num1, String num2) {
        if (num1.length() > num2.length()) {
            return true;
        }
        if (num1.length() < num2.length()) {
            return false;
        }
        // 比较返回结果
        return num1.compareTo(num2) > 0;
    }
}
